const chalk = require('chalk');
const fs = require('fs');
const { glob } = require('glob');
const { isStringAndHasLength, collectInChinese, formatDate } = require('../../helper.js');
const ora = require('ora');

/**
 * @description 查找逻辑
 */
async function find11Handler({ exportFile, fileOrDirString }) {
    let spinner = null;
    let chinesStringArr = [];
    try {
        const fileArr = fileOrDirString.split('&').filter((el) => isStringAndHasLength(el));
        if (fileArr.length === 0) {
            return console.log(chalk.red(`参数有误，请检查输入`));
        }
        spinner = ora('查询中...').start();

        const jsfiles = await glob(fileArr, {
            ignore: 'node_modules/**',
        });

        console.log(jsfiles);

        for await (const fileUrl of jsfiles) {
            try {
                const res = await collectInChinese(fileUrl);
                chinesStringArr.push(res);
            } catch (error) {}
        }
    } catch (error) {
        console.log('一个错误-3478953:', error);
    } finally {
        spinner?.stop?.();
        const arr = chinesStringArr.flat(8888);

        if (arr.length === 0) {
            console.log(chalk.red('暂时没有找到中文，请确认'));
            return;
        }

        const chinesArr = Array.from(new Set(arr)).join('\n');

        fs.writeFile(exportFile || `aci18n_11_${formatDate()}.txt`, chinesArr, 'utf8', function (err) {
            if (err) {
                console.log(chalk.magenta('导出出错啦，请检查'));
                return;
            }
            console.log(chalk.magenta('文件：已经导出，请检查'));
        });
    }
}

module.exports = {
    find11Handler,
};
